package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 129. 求根节点到叶节点数字之和
 * 广度优先搜索
 * 维护两个队列，分别存储节点和节点对应的数字。
 *
 * @author fy
 * @date 2022/4/25 11:45
 */
public class Solution129_3 {

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> nodeStack = new LinkedList<>();
        Deque<Integer> valStack = new LinkedList<>();
        nodeStack.offer(root);
        valStack.offer(root.val);
        int sum = 0;
        while (!nodeStack.isEmpty()) {
            TreeNode node = nodeStack.poll();
            int val = valStack.poll();
            TreeNode left = node.left;
            TreeNode right = node.right;
            if (left == null && right == null) {
                sum += val;
                continue;
            }
            if (left != null) {
                nodeStack.push(left);
                valStack.push(left.val + val * 10);
            }
            if (right != null) {
                nodeStack.push(right);
                valStack.push(right.val + val * 10);
            }
        }
        return sum;
    }

}
